package dao

import (
	"fmt"
	"github.com/cihub/seelog"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
	"shop/config"
	"time"
)

var mysqlCli = initMysql()

func initMysql() *gorm.DB {
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True",
		config.Conf.MysqlUsername, config.Conf.MysqlPassword, config.Conf.MysqlAddress, config.Conf.MysqlDBName)
	var err error
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{NamingStrategy: schema.NamingStrategy{
		TablePrefix:   "",
		SingularTable: true,
	}})
	if err != nil {
		log.Panicln("fail to connect mysql, err:", err)
		return db
	}

	seelog.Trace("success connect mysql, db:", db)
	sqlDB, err := db.DB()
	if err != nil {
		log.Panicln("connect db server failed.")
		return db
	}
	// 配置数据库连接池
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Minute * 10)
	return db
}

func GetDB() *gorm.DB {
	return mysqlCli
}

func GetTx() *gorm.DB {
	return mysqlCli.Begin()
}
